package com.gin.danbooru.response.detail

import com.gin.danbooru.enums.Rating
import com.gin.danbooru.response.DocumentEntity
import com.gin.danbooru.response.field.PostsTags
import com.gin.danbooru.response.search.PostsPreview
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.util.regex.Pattern

/**
 * 作品详情
 * @author BX-Gin
 * @from 2024/2/27 13:38
 */
class PostsDetail(document: Document) : DocumentEntity(document) {
    // 标签信息

    var artists: List<PostsTags>? = null
    var copyright: List<PostsTags>? = null
    var characters: List<PostsTags>? = null
    var general: List<PostsTags>? = null
    var meta: List<PostsTags>? = null

    // 作品信息
    var families: List<PostsPreview>? = null

    var id: Long? = null
    var uploaderId: Long? = null
    var uploaderName: String? = null
    var size: String? = null
    var width: Int? = null
    var height: Int? = null
    var source: String? = null
    var rating: Rating? = null
    var score: Int? = null
    var favorites: Int? = null
    var status: String? = null

    var url: String? = null
    var description: String? = null
    var descriptionHtml: String? = null

    init {
        val tagList = document.getElementById("tag-list")!!
        artists = findTagList(tagList, "artist-tag-list")
        copyright = findTagList(tagList, "copyright-tag-list")
        characters = findTagList(tagList, "character-tag-list")
        general = findTagList(tagList, "general-tag-list")
        meta = findTagList(tagList, "meta-tag-list")
        // id
        id = document.getElementById("post-info-id")!!.text().replace("ID: ", "").toLong()
        // 上传者
        val users = document.select("#post-info-uploader>.user")
        if (!users.isEmpty()) {
            uploaderId = users[0]?.attr("data-user-id")?.toLong()
            uploaderName = users[0]?.attr("data-user-name")
        }
        // 大小
        val sizeElement = document.getElementById("post-info-size")!!
        size = sizeElement.getElementsByTag("a")[0].text()
        val matcher = SIZE_PATTERN.matcher(sizeElement.text())
        if (matcher.find()) {
            width = matcher.group(1).toInt()
            height = matcher.group(2).toInt()
        }
        //来源
        val links = document.select("#post-info-source>a")
        if (!links.isEmpty()) {
            source = links[0].attr("href")
        }

        rating = Rating.find(document.getElementById("post-info-rating")!!.text().replace("Rating: ", ""))

        score = document.select("#post-info-score .post-score")[0].text().toInt()
        favorites = document.select("#post-info-favorites .post-favcount")[0].text().toInt()
        status = document.getElementById("post-info-status")!!.text().replace("Status: ", "").trim()
        url = document.select("#post-option-download>a")[0].attr("href")

        val familyContainer = document.getElementById("has-parent-relationship-preview")
        if (familyContainer != null) {
            families = familyContainer.getElementsByTag("article").map { PostsPreview(it) }
        }

        val descriptionElement = document.getElementById("original-artist-commentary")
        if (descriptionElement != null) {
            description = descriptionElement.text()
            descriptionHtml = descriptionElement.html()
        }
    }

    companion object {
        val SIZE_PATTERN = Pattern.compile("(\\d+)x(\\d+)")

        /**
         * 从父节点中找到指定class名称的标签列表
         */
        @JvmStatic
        fun findTagList(parent: Element, className: String): List<PostsTags> {
            val elements = parent.getElementsByClass(className)
            if (elements.isEmpty()) {
                return listOf()
            }
            val listItems = parent.select(".${className}>li")
            if (listItems.isEmpty()) {
                return listOf()
            }

            return listItems.map { PostsTags(it) }
        }
    }
}